import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../models/expense.dart';
import '../services/database_service.dart';
import '../utils/constants.dart';
import '../screens/add_expense_screen.dart';
import '../screens/category_details_screen.dart';
import '../screens/daily_expenses_screen.dart';
import 'package:intl/intl.dart';

class HomeScreen extends StatefulWidget {
  final bool showSuccess;
  const HomeScreen({super.key, this.showSuccess = false});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final DatabaseService _databaseService = DatabaseService();
  Map<String, double> _categoryTotals = {};
  Map<String, double> _recentDailyTotals = {};
  Map<String, double> _monthlyDailyTotals = {};
  bool _isLoading = true;
  final DateTime _currentDate = DateTime.now();

  @override
  void initState() {
    super.initState();
    _loadData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.showSuccess) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('记账成功！', textAlign: TextAlign.center),
            backgroundColor: Colors.green,
            behavior: SnackBarBehavior.floating,
            margin: const EdgeInsets.fromLTRB(40, 0, 40, 80),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(12))),
            duration: Duration(seconds: 2),
          ),
        );
      }
    });
  }

  Future<void> _loadData() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // Load category totals for current month
      final categoryTotals =
          await _databaseService.getCategoryTotalsForMonth(_currentDate);

      // Load recent 3 days totals (yesterday, day before yesterday, and day before that)
      final yesterday =
          DateTime(_currentDate.year, _currentDate.month, _currentDate.day)
              .subtract(const Duration(days: 1));
      final recentStartDate = yesterday.subtract(const Duration(days: 2));
      final recentDailyTotals =
          await _databaseService.getDailyTotalsForDateRange(
        recentStartDate,
        DateTime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59),
      );

      // Load monthly daily totals (including today)
      final monthStartDate = DateTime(_currentDate.year, _currentDate.month, 1);
      final monthlyDailyTotals =
          await _databaseService.getDailyTotalsForDateRange(
        monthStartDate,
        DateTime(_currentDate.year, _currentDate.month, _currentDate.day, 23,
            59, 59),
      );

      if (!mounted) return;

      setState(() {
        _categoryTotals = categoryTotals;
        _recentDailyTotals = recentDailyTotals;
        _monthlyDailyTotals = monthlyDailyTotals;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget _buildCategorySection() {
    if (_categoryTotals.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.all(16.0),
          child: Row(
            children: [
              Icon(Icons.pie_chart, color: Colors.orange),
              SizedBox(width: 8),
              Text(
                '本月分类统计',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 16),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 1.5,
            crossAxisSpacing: 12,
            mainAxisSpacing: 12,
          ),
          itemCount: _categoryTotals.length,
          itemBuilder: (context, index) {
            final category = _categoryTotals.keys.elementAt(index);
            final amount = _categoryTotals[category]!;
            final color = Color(Constants.categoryColors[category]!);

            return GestureDetector(
              onTap: () => _navigateToCategoryDetails(category),
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      color.withOpacity(0.8),
                      color.withOpacity(0.6),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: color.withOpacity(0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 10.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.2),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Icon(
                              _getCategoryIcon(category),
                              color: Colors.white,
                              size: 20,
                            ),
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Text(
                              category,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 0),
                      Text(
                        '¥${amount.toStringAsFixed(2)}',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
        const SizedBox(height: 16),
      ],
    );
  }

  IconData _getCategoryIcon(String category) {
    switch (category) {
      case '餐饮':
        return Icons.restaurant;
      case '交通':
        return Icons.directions_car;
      case '购物':
        return Icons.shopping_bag;
      case '娱乐':
        return Icons.movie;
      case '医疗':
        return Icons.local_hospital;
      case '教育':
        return Icons.school;
      case '住房':
        return Icons.home;
      case '其他':
        return Icons.more_horiz;
      default:
        return Icons.category;
    }
  }

  void _navigateToCategoryDetails(String category) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CategoryDetailsScreen(
          category: category,
          currentMonth: _currentDate,
        ),
      ),
    );
  }

  Widget _buildRecentDaysList() {
    final yesterday =
        DateTime(_currentDate.year, _currentDate.month, _currentDate.day)
            .subtract(const Duration(days: 1));
    final days = List.generate(3, (index) {
      final date = yesterday.subtract(Duration(days: 2 - index));
      final dateStr = DateFormat('yyyy-MM-dd').format(date);
      final total = _recentDailyTotals[dateStr] ?? 0.0;
      return _buildRecentDayItem(date, total);
    });

    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.all(16.0),
          child: Row(
            children: [
              Icon(Icons.history, color: Colors.blue),
              SizedBox(width: 8),
              Text(
                '最近三天',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
        ...days,
      ],
    );
  }

  Widget _buildRecentDayItem(DateTime date, double total) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        title: Text(
          '${date.year}年${date.month}月${date.day}日',
        ),
        trailing: Text(
          '¥${total.toStringAsFixed(2)}',
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => DailyExpensesScreen(date: date),
            ),
          );
        },
      ),
    );
  }

  Widget _buildMonthlyChart() {
    if (_monthlyDailyTotals.isEmpty) {
      return const SizedBox.shrink();
    }

    final spots = _monthlyDailyTotals.entries.map((entry) {
      final date = DateTime.parse(entry.key);
      return FlSpot(
        date.day.toDouble(),
        entry.value,
      );
    }).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(
            '本月支出趋势',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        SizedBox(
          height: 200,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: LineChart(
              LineChartData(
                gridData: const FlGridData(show: false),
                titlesData: FlTitlesData(
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                        showTitles: true,
                        reservedSize: 40,
                        getTitlesWidget: (value, meta) {
                          if (value % 50 == 0) {
                            return Text('¥${value.toInt()}');
                          }
                          return const SizedBox.shrink();
                        }),
                  ),
                  rightTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        if (value.toInt() % 5 == 0) {
                          return Text(
                            value.toInt().toString(),
                            style: const TextStyle(fontSize: 10),
                          );
                        }
                        return const Text('');
                      },
                    ),
                  ),
                ),
                borderData: FlBorderData(
                    show: true,
                    border: const Border.symmetric(
                        horizontal: BorderSide(), vertical: BorderSide())),
                minX: 1,
                maxX: 31,
                minY: 0,
                // maxY: 可自动
                lineBarsData: [
                  LineChartBarData(
                    spots: spots,
                    isCurved: true,
                    color: Colors.blue,
                    barWidth: 3,
                    isStrokeCapRound: true,
                    dotData: const FlDotData(show: true),
                    belowBarData: BarAreaData(
                      show: true,
                      color: Colors.blue.withOpacity(0.1),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('记账本'),
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadData,
              child: ListView(
                children: [
                  _buildCategorySection(),
                  const Divider(),
                  _buildRecentDaysList(),
                  const Divider(),
                  _buildMonthlyChart(),
                ],
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final result = await Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const AddExpenseScreen()),
          );
          if (result == true) {
            _loadData();
          }
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
